//
//  MallReccomendViewController.m
//  CYWFrame
//
//  Created by 于顺燊 on 2018/8/15.
//  Copyright © 2018年 Macx. All rights reserved.
//

#import "MallReccomendViewController.h"
#import "MallHomeViewController.h"
#import <XRCarouselView.h>
#import "MallsCollectionViewCell.h"
#import "AdsServer.h"
#import "Goods.h"
//#import "MallClassificationViewController.h"
#import "MallDetailViewController.h"
#import "SearchViewController.h"
#import "MallClassViewController.h"
#import "MKJShoppingCartViewController.h"

@interface MallReccomendViewController ()<UICollectionViewDelegate, UICollectionViewDataSource>
@property (nonatomic, assign) NSInteger page; // 网络请求页数
@property (nonatomic, strong) NSMutableArray *infoArr;

@end

@implementation MallReccomendViewController {
	UIView          *_headBgView;
	UIButton        *_returnBtn;
	UIButton        *_shopCarBtn;
	UIButton        *_shopSpeciesBtn;
	XRCarouselView  *_carouselView;
	UIButton        *_recommendBtn;
	
	UICollectionView *_collectionView;
	MallsCollectionViewCell *_item;
	
	CGFloat         _collectionW;
	CGFloat         _collectionH;
}

- (void)viewDidLoad {
	[super viewDidLoad];
	// Do any additional setup after loading the view.
	
	self.page = 1;
	
	[self GETMallsGoods];
	
	[self createUI];
	
	//[self GETAds];
	
	[self refreshData];
}


#pragma mark ==========构建UI==========
- (void)createUI {
	
	self.view.backgroundColor = UISeparatedColorRGB;
	
	_headBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64)];
	//[self.view addSubview:_headBgView];
	_headBgView.backgroundColor = UIMainColorRGB;
	
	// 返回btn
	_returnBtn = [UIButton buttonWithType:UIButtonTypeCustom];
	//[_headBgView addSubview:_returnBtn];
	[_returnBtn setImage:IMAGE(@"return") forState:UIControlStateNormal];
	[_returnBtn addTarget:self action:@selector(returnClick:) forControlEvents:UIControlEventTouchUpInside];
	_returnBtn.frame = CGRectMake(0, 20, 44, 44);
	
	UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(44, 0, SCREEN_WIDTH-132, 30)];
	searchBar.centerY = _returnBtn.centerY;
	searchBar.placeholder = @"请输入搜索内容…";
	searchBar.backgroundImage = IMAGE(@"clearImage");
	searchBar.layer.cornerRadius = searchBar.height/2;
	searchBar.layer.masksToBounds = YES;
	UIView *searchTextField = searchTextField = [searchBar valueForKey:@"_searchField"];
	searchTextField.backgroundColor = [UIColor colorWithRed:234/255.0 green:235/255.0 blue:237/255.0 alpha:1];
	//    [_searchBar addTarget:self action:@selector(searchClicK:)];
	[_headBgView addSubview:searchBar];
	
	UIView *searView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, searchBar.width, searchBar.height)];
	[searchBar addSubview:searView];
	[searView addTarget:self action:@selector(searchClicK:)];
	
	
	
	_shopCarBtn = [UIButton buttonWithType:UIButtonTypeCustom];
	[_headBgView addSubview:_shopCarBtn];
	[_shopCarBtn setImage:IMAGE(@"icon_shopcar") forState:UIControlStateNormal];
	[_shopCarBtn addTarget:self action:@selector(cartClick:) forControlEvents:UIControlEventTouchUpInside];
	_shopCarBtn.frame = CGRectMake(SCREEN_WIDTH-88, 20, 44, 44);
	
	_shopSpeciesBtn = [UIButton buttonWithType:UIButtonTypeCustom];
	[_headBgView addSubview:_shopSpeciesBtn];
	[_shopSpeciesBtn setImage:IMAGE(@"icon_classify") forState:UIControlStateNormal];
	[_shopSpeciesBtn addTarget:self action:@selector(speciesClick:) forControlEvents:UIControlEventTouchUpInside];
	_shopSpeciesBtn.frame = CGRectMake(SCREEN_WIDTH-44, 20, 44, 44);
	
	/*
	_carouselView = [[XRCarouselView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SW(5)*2)];
	//    [_scrollView addSubview:_carouselView];
	_carouselView.contentMode = UIViewContentModeScaleAspectFill;
	_carouselView.imageArray = @[IMAGE(@"img.jpg")];
	_carouselView.time = 2;
	
	_recommendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
	[_recommendBtn setImage:IMAGE(@"icon_recommend") forState:UIControlStateNormal];
	[_recommendBtn setTitle:@" 为你推荐" forState:UIControlStateNormal];
	_recommendBtn.titleLabel.font = kUHSystemFontWithSize(13);
	[_recommendBtn setTitleColor:kGrayColor forState:UIControlStateNormal];
	CGSize vipSize = [LZCTools textSizeWithText:_recommendBtn.titleLabel.text font:kUHSystemFontWithSize(13)];
	_recommendBtn.frame = CGRectMake(0, _carouselView.height, vipSize.width+5+SW(16), SW(12));
	_recommendBtn.centerX = self.view.centerX;
	 */
	
	// collectionView
	
	// 集合视图 collectionView所有布局的父类
	// 系统提供自带的布局类
	UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
	// 默认为纵向滑动
	flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
	flowLayout.minimumInteritemSpacing = 10;
	flowLayout.minimumLineSpacing = 10;
	
	// 创建collectionView
	_collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, self.view.height-64) collectionViewLayout:flowLayout];
	[self.view addSubview:_collectionView];
	_collectionView.backgroundColor = UISeparatedColorRGB;
	_collectionView.delegate = self;
	_collectionView.dataSource = self;
	
	[_collectionView registerNib:[UINib nibWithNibName:@"MallsCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"item"];
	
	//flowLayout.headerReferenceSize = CGSizeMake(0, SW(5)*2+SW(12));
	//注册头视图
	/*
	[_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionViewHeader"];
	 */
	
	CGSize size1 = [LZCTools textSizeWithText:@"x" font:kUHSystemFontWithSize(12)];
	
	_collectionW = (SCREEN_WIDTH-30)/2;
	_collectionH = _collectionW+20+size1.height*3;
	
}

#pragma mark ==========UICollectionView==========
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
	
	_item = [collectionView dequeueReusableCellWithReuseIdentifier:@"item" forIndexPath:indexPath];
	
	_item.model = self.infoArr[indexPath.row];
	
	return _item;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
	return self.infoArr.count;
}
//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
	//    NSLog(@"%f", _item.cover.height);
	//    return CGSizeMake((SCREEN_WIDTH-30)/2, _item.money.y+_item.money.height+10);
	return CGSizeMake(_collectionW, _collectionH);
}
//定义每个UICollectionView 的 margin
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
	return UIEdgeInsetsMake(10, 10, 10, 10);
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
	
	NSLog(@"点击collectionView.item = %ld", indexPath.row);
	
	Goods *model = self.infoArr[indexPath.row];
	
	MallDetailViewController *detailVC = [[MallDetailViewController alloc] init];
	detailVC.goodId = model.goods_id;
	detailVC.isBuytogetherMode = model.is_ecbuy;
	[self.navigationController pushViewController:detailVC animated:YES];
	
}
//创建头视图
/*
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
		   viewForSupplementaryElementOfKind:(NSString *)kind
								 atIndexPath:(NSIndexPath *)indexPath {
	
	UICollectionReusableView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionViewHeader" forIndexPath:indexPath];
	[headView addSubview:_carouselView];
	[headView addSubview:_recommendBtn];
	headView.backgroundColor = kWhiteColor;
	
	return headView;
}
 */


#pragma mark ==========更新数据==========
- (void)refreshData {
	__weak typeof (self) weakSelf = self;
	
	_collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
		NSLog(@"上拉加载");
		weakSelf.page++;
		[weakSelf GETMallsGoods];
	}];
	
}

#pragma mark ===========响应方法==========
- (void)GETMallsGoods {
	
	if (!self.keyword) {
		self.keyword = @"";
	}
	
	NSDictionary *param;
	NSString *urlStr;
	if (self.type == 0) {
		urlStr = APIRecommendGoods;
		param =  @{@"per_page":@"6", @"page":[NSString stringWithFormat:@"%ld", self.page]};
	}
	else {
		urlStr = APIMallsGoods;
		param = @{
				  @"per_page":@"6",
				  @"page":[NSString stringWithFormat:@"%ld", self.page],
				  @"keyword":self.keyword
				  };
	}
	NSLog(@"keyword is %@", self.keyword);
	[[NetworkTool sharedTool] requestWithName:@"获取商品" URLString:urlStr parameters:param method:@"GET" callBack:^(id responseObject) {
		
		NSArray *arr = responseObject[@"data"];
		if (self.page == 1) {
			[self.infoArr removeAllObjects];
		}
		
		if (arr.count == 0) {
			self.page--;
			if (self.page == 0) {
				self.page = 1;
			}
		}
		
		for (NSDictionary *dic in arr) {
			Goods *model = [[Goods alloc] init];
			[model setValuesForKeysWithDictionary:dic];
			[self.infoArr addObject:model];
		}
		
		dispatch_async(dispatch_get_main_queue(), ^{
			[MBProgressHUD hideHUDForView:self.view animated:YES];
			[_collectionView.mj_header endRefreshing];
			[_collectionView.mj_footer endRefreshing];
			[_collectionView reloadData];
		});
		
	}];
}

// 获取广告
- (void)GETAds {
	
	[AdsServer GETAds:@{@"board":@"app_mall"} xrView:_carouselView];
	
}

// 返回
- (void)returnClick:(UIButton *)sender {
	[self.navigationController popViewControllerAnimated:YES];
}
// 进入商品分类
- (void)speciesClick:(UIButton *)sender {
	//        [self.navigationController pushViewController:[[MallClassificationViewController alloc] init] animated:YES];
	//    [self.navigationController pushViewController:[[MallClassViewController alloc] init] animated:YES];
}
// 进入购物车列表
- (void)cartClick:(UIButton *)sender {
	//    MallShopCartViewController *cartVC = [[MallShopCartViewController alloc] init];
	//    [self.navigationController pushViewController:cartVC animated:YES];
	MKJShoppingCartViewController *shop = [MKJShoppingCartViewController new];
	[self.navigationController pushViewController:shop animated:YES];
}

// 商品搜索
- (void)searchClicK:(id)sender {
	SearchViewController *searchVC = [[SearchViewController alloc] init];
	searchVC.type = 3;
	[self.navigationController pushViewController:searchVC animated:YES];
}


// 懒加载
- (NSMutableArray *)infoArr {
	if (_infoArr == nil) {
		_infoArr = [[NSMutableArray alloc] init];
	}
	return _infoArr;
}

- (void)setKeyword:(NSString *)keyword
{
	if (_keyword != keyword) {
		_keyword = keyword;
	}
	self.page = 1;
	[self GETMallsGoods];
}

- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning];
	// Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
